﻿#if NETSTANDARD2_0_OR_GREATER || NETCOREAPP2_0_OR_GREATER
using Jack.RedisLib;
#endif

namespace Jack.SequentialGuid
{
#if NETSTANDARD2_0_OR_GREATER || NETCOREAPP2_0_OR_GREATER
	/// <summary>
	/// 分布式id生成服务
	/// </summary>
	public class IdGeneratorService
	{
		private readonly IRedisClient _redisClient;
		private readonly IIdGenerator _idGenerator;

		/// <summary>
		/// <inheritdoc/>
		/// </summary>
		public IdGeneratorService(IRedisClient redisClient, IIdGenerator idGenerator)
		{
			_redisClient = redisClient;
			_idGenerator = idGenerator;
		}

		/// <summary>
		/// 生成唯一分布式id
		/// </summary>
		/// <param name="prefix"></param>
		/// <returns></returns>
		public async Task<string> NewId(string prefix)
		{
			var newId = $"{prefix}{_idGenerator.NewId():n}";

			string incrementKey = $"{newId}:_Increment_";
			if (await _redisClient.StringIncrement(incrementKey, 1) == 1)
			{
				await _redisClient.KeyExpire(incrementKey, TimeSpan.FromSeconds(3));
				return newId;
			}

			return await NewId(prefix);
		}
	}
#endif
}
